package com.teufandsub.socialproximity.gui;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.teufandsub.socialproximity.R;
import com.teufandsub.socialproximity.controller.Constants;
import com.teufandsub.socialproximity.controller.Controller;
import com.teufandsub.socialproximity.controller.Utils;
import com.teufandsub.socialproximity.logic.RegistrationInfo;

public class SignUpActivity extends SherlockActivity implements OnClickListener {
	
	/* The sign up Activity */
	private static final String EMAIL_PATTERN = 
			"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	
    //Registration response code
	private final int CODE_REGISTRATION_OKAY = 0;
	private final int CODE_USERNAME_EXISTING = 1;
	private final int CODE_PROBLEM_PERSISTING = 2;
	
	private EditText et_email,et_passwd,et_confPasswd,et_firstname,et_surname,et_username;
	private DatePicker dp;
	private RadioGroup rg;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_signup);
		
		dp = (DatePicker) findViewById(R.id.day_dp);  
	    et_firstname  = (EditText) findViewById(R.id.firstname_et);    
	    et_surname    = (EditText) findViewById(R.id.surname_et);	    
	    et_username   = (EditText) findViewById(R.id.pseudo_et);
	    et_email      = (EditText) findViewById(R.id.email_et);
	    et_passwd     = (EditText) findViewById(R.id.password_et);
	    et_confPasswd = (EditText) findViewById(R.id.conf_password_et);
	    rg = (RadioGroup) findViewById(R.id.radio_group_gender); 
	    
	    Button sign_up = (Button) findViewById(R.id.button_signup);
	    sign_up.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		
		final String firstname = et_firstname.getText().toString();
		final String surname = et_surname.getText().toString();
		final String username = et_username.getText().toString();
		final String email = et_email.getText().toString();
		final String passwd = et_passwd.getText().toString();
		final String conf_passwd = et_confPasswd.getText().toString();
		final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
		 calendar.set(dp.getYear(),dp.getMonth(),dp.getDayOfMonth(), 0, 0, 0);
		final Date date = calendar.getTime();
		final int sex;
		
		switch(rg.getCheckedRadioButtonId()){
	    	case R.id.gender_male :     sex = RegistrationInfo.SEX_MALE; break;
	    	case R.id.gender_female:    sex = RegistrationInfo.SEX_FEMALE; break;
	    	case R.id.gender_dont_show: sex = RegistrationInfo.SEX_UNKNOWN; break;
	    	default: sex = -1;
	    }
		
		switch(v.getId()){
			case R.id.button_signup :
				AsyncTask<Void, Void, Integer> th = new AsyncTask<Void, Void, Integer>() {
					
					ProgressDialog dialog;
					
					@Override
					protected void onPreExecute() {
						super.onPreExecute();
						dialog = ProgressDialog.show(SignUpActivity.this, "", getResources().getString(R.string.loading), true);
					}
					@Override
					protected Integer doInBackground(Void... params) {
						return Controller.getInstance().register(SignUpActivity.this,
								new RegistrationInfo(firstname, surname, username, email, Utils.toMD5(passwd), date, sex));
					}
					
					@Override
					protected void onPostExecute(Integer result) {
						super.onPostExecute(result);
						dialog.dismiss();
						switch(result){
							case CODE_REGISTRATION_OKAY:
								Toast.makeText(SignUpActivity.this, getResources().getString(R.string.registration_succes), Toast.LENGTH_LONG).show();
								Intent i = new Intent(SignUpActivity.this, LoginActivity.class);
								startActivity(i);
								break;
							case CODE_USERNAME_EXISTING:
								Toast.makeText(SignUpActivity.this, getResources().getString(R.string.registration_failed), Toast.LENGTH_LONG).show();
								break;
							case CODE_PROBLEM_PERSISTING:Log.e(Constants.APP_NAME, "Registration problem persisting");break;
							default:Log.e(Constants.APP_NAME, "Error during registration" + result );
						}
					}
				};
				
				
				if(firstname.isEmpty() || surname.isEmpty() || username.isEmpty() || email.isEmpty() || 
						passwd.isEmpty() || conf_passwd.isEmpty()){
					
					Toast.makeText(this, getResources().getString(R.string.empty_field), Toast.LENGTH_LONG).show();
					
				}else{
					if(!passwd.equals(conf_passwd)){
						Toast.makeText(this, getResources().getString(R.string.different_passwd), Toast.LENGTH_LONG).show();
						et_passwd.setText("");
						et_confPasswd.setText("");
					}else if(!validateEmail(email)){
						Toast.makeText(this, getResources().getString(R.string.invalide_email), Toast.LENGTH_LONG).show();
					}else{
						if(Utils.hasConnectivity(this)){
							th.execute();
						}else{
							Toast.makeText(this, getResources().getString(R.string.no_connectivity), Toast.LENGTH_LONG).show();
						}
					}
				}
				break;
		}
		
	}
	
	private boolean validateEmail(String address){
		Pattern pattern = Pattern.compile(EMAIL_PATTERN);
		Matcher matcher = pattern.matcher(address);
			
		return matcher.matches();
	}
}
